﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Configuration;

namespace DotNETX.Version.Update
{
    public class UpdateViewModel : BaseViewModel
    {
        public const string CONFIGKEY_SERVER_VIRTUALDIRECTORY = "DotNETX.Version.Update.ServerVirtualDirectory";
        public const string CONFIGKEY_RELEASE_DIRECTORY = "DotNETX.Version.Update.ReleaseDirectory";
        public const string CONFIGKEY_TEMP_DIRECTORY = "DotNETX.Version.Update.TempDirectory";

        public const string CONFIGKEY_VERSIONSERVICE_IP = "DotNETX.Version.Update.VersionServiceIp";
        public const string CONFIGKEY_VERSIONSERVICE_PORT = "DotNETX.Version.Update.VersionServicePort";
        public const string CONFIGKEY_VERSIONSERVICE_PROTOCAL = "DotNETX.Version.Update.VersionServiceProtocal";

        public const string CONFIGKEY_FILESERVICE_IP = "DotNETX.Version.Update.FileServiceIp";
        public const string CONFIGKEY_FILESERVICE_PORT = "DotNETX.Version.Update.FileServicePort";
        public const string CONFIGKEY_FILESERVICE_PROTOCAL = "DotNETX.Version.Update.FileServiceProtocal";

        string VirtualDir { get; set; }
        string ReleaseDir { get; set; }
        string TempDir { get; set; }

        string VersionServiceIp { get; set; }
        int VersionServicePort { get; set; }
        string VersionServiceProtocal { get; set; }
        string FileServiceIp { get; set; }
        int FileServicePort { get; set; }
        string FileServiceProtocal { get; set; }

        public UpdateViewModel()
        {
            if (!App.IsInDesignMode)
            {
                ReadConfig();
                Status = "连接服务器...";
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += (s, e) =>
                {
                    try
                    {
                        Initial();
                        e.Result = true;
                    }
                    catch (Exception ex)
                    {
                        e.Result = false;
                        throw ex;
                    }
                };
                bw.RunWorkerCompleted += (s, e) =>
                {
                    if (false == (bool)e.Result)
                    {
                        Status = string.Format("无法初始化!");
                    }
                    else
                    {
                        try
                        {
                            UpgradeClient.DownloadPakage(ReleaseDir);
                        }
                        catch
                        {
                            Status = string.Format("无法连接服务器！");
                        }
                    }
                };
                bw.RunWorkerAsync();
            }
        }

        public void ReadConfig()
        {
            Type type = this.GetType();
            VirtualDir = TryGetAppSetting(type, CONFIGKEY_SERVER_VIRTUALDIRECTORY);
            ReleaseDir = TryGetAppSetting(type, CONFIGKEY_RELEASE_DIRECTORY);
            TempDir = TryGetAppSetting(type, CONFIGKEY_TEMP_DIRECTORY);

            VersionServiceIp = TryGetAppSetting(type, CONFIGKEY_VERSIONSERVICE_IP);
            VersionServicePort = int.Parse(TryGetAppSetting(type, CONFIGKEY_VERSIONSERVICE_PORT));
            VersionServiceProtocal = TryGetAppSetting(type, CONFIGKEY_VERSIONSERVICE_PROTOCAL);

            FileServiceIp = TryGetAppSetting(type, CONFIGKEY_FILESERVICE_IP);
            FileServicePort = int.Parse(TryGetAppSetting(type, CONFIGKEY_FILESERVICE_PORT));
            FileServiceProtocal = TryGetAppSetting(type, CONFIGKEY_FILESERVICE_PROTOCAL);
        }
        private static string TryGetAppSetting(Type type, string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(type.Assembly.Location);
            if (config.AppSettings.Settings.AllKeys.Contains(key))
            {
                return config.AppSettings.Settings[key].Value;
            }
            else
            {
                return ConfigurationManager.AppSettings[key];
            }
        }

        VersionClient VersionClient = null;
        FileServer.FileManagerClient FilemgrClient = null;
        UpgradeClient UpgradeClient = null;

        public void Initial()
        {
            VersionClient = VersionClient.Create(VersionServiceIp, VersionServicePort, VersionServiceProtocal);
            FilemgrClient = FileServer.FileManagerClient.Create(FileServiceIp, FileServicePort, FileServiceProtocal);
            UpgradeClient = new UpgradeClient(VirtualDir, VersionClient, FilemgrClient);
            UpgradeClient.TempFolder = TempDir;
            UpgradeClient.DownloadPackageStart += () => { Status = "下载升级包..."; };
            UpgradeClient.DownloadPackageProgress += (p) => { Progress = p * 100; };
            UpgradeClient.DownloadPackageComplete += (r) => { };

            UpgradeClient.ExtractPackageStart += () => { Status = "解压升级包..."; };
            UpgradeClient.ExtractPackageProgress += (p) => { Progress = p * 100; };
            UpgradeClient.ExtractPackageComplete += (r) => { Status = "升级完成"; };
        }

        private double _progress = 0;
        public double Progress
        {
            get
            {
                return _progress;
            }
            set
            {
                _progress = value;
                NotifyPropertyChanged("Progress");
            }
        }

        private string _status = "";
        public string Status
        {
            get { return _status; }
            set
            {
                _status = value;
                NotifyPropertyChanged("Status");
            }
        }
    }
}
